package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.entities.community.ComMsgCollect;
import com.maiji.cloud.entities.community.ComMsgInfo;
import com.maiji.cloud.entities.community.ComPraise;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.entities.login.UserInfo;
import com.maiji.cloud.mapper.ComMsgInfoMapper;
import com.maiji.cloud.mapper.ComPraiseMapper;
import com.maiji.cloud.microservice.UserInfoService;
import com.maiji.cloud.request.BaseInputDto;
import com.maiji.cloud.request.IdInputDto;
import com.maiji.cloud.request.community.ComUserMessageInputDto;
import com.maiji.cloud.request.shopingmall.DistributeIntegralReqDto;
import com.maiji.cloud.response.BaseOutPutDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.login.UserInfoResData;
import com.maiji.cloud.response.shopingmall.FinancialDetailsResData;
import com.maiji.cloud.service.AsyncService;
import com.maiji.cloud.service.ComPraiseService;
import com.maiji.cloud.service.IntegralService;
import com.maiji.cloud.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import java.sql.Time;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.springframework.beans.BeanUtils.copyProperties;

@Service
@Transactional

public class ComPraiseServiceImpl  extends ServiceImpl<ComPraiseMapper,ComPraise> implements ComPraiseService{

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ComMsgInfoMapper comMsgInfoMapper;

    @Autowired
    private ComPraiseMapper comPraiseMapper;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private IntegralService integralService;

    /**
     * 动态点赞
     * @param inputDto
     * @param maijiToken
     * @return
     */
    @Override
    public BaseOutPutDto<FinancialDetailsResData> praise(@RequestBody BaseInputDto<IdInputDto> inputDto, @RequestHeader("maijiToken")String maijiToken){

        BaseOutPutDto<FinancialDetailsResData> outPutDto = new BaseOutPutDto();

        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();
        try{

            ComPraise comPraise = new ComPraise();
            comPraise.setPraiserId(userId);
            comPraise.setBelongId(inputDto.getData().getId());

            ComMsgInfo msgInfo = comMsgInfoMapper.selectById(inputDto.getData().getId());

            ComPraise selectOne = comPraiseMapper.selectOne(comPraise);
            if(selectOne != null){
                if(selectOne.getDel() == 1){
                    if(comPraiseMapper.update(new ComPraise().setDel(0) ,new EntityWrapper(selectOne)) >0){
                        msgInfo.setPraise_count(msgInfo.getPraise_count()+1);
                        outPutDto.setStatus(Status.SUCCESS);
                        outPutDto.setMessage("点赞成功");
                    }
                }else{
                    outPutDto.setStatus(Status.ERROR);
                    outPutDto.setMessage("点赞失败");
                }
            }else{

                comPraise.setPraiseTime(TimeUtil.getCurDateStamp());
                if( comPraiseMapper.insert(comPraise) > 0){
                    msgInfo.setPraise_count(msgInfo.getPraise_count()+1);
                    outPutDto.setStatus(Status.SUCCESS);
                    outPutDto.setMessage("点赞成功");

                    {
                        ComUserMessageInputDto messageInputDto = new ComUserMessageInputDto();
                        messageInputDto.setContent("赞了你的动态");
                        messageInputDto.setSourceUserId(userId);
                        messageInputDto.setTargetUserId(msgInfo.getUserId());
                        messageInputDto.setType(ComUserMessageTypeEnum.Praise.getValue());
                        messageInputDto.setMsgId(msgInfo.getMsgId());
                        asyncService.asycCreateMessage(messageInputDto);

                    }

                    //用户每天第一次点赞 有积分
                    EntityWrapper<ComPraise> entityWrapper = new EntityWrapper<>();
                    ComPraise countCompraise = new ComPraise();
                    countCompraise.setPraiserId(userId);
                    entityWrapper.setEntity(countCompraise);
                    Long startTime = TimeUtil.getZeroTime(new Date()).getTime();
                    Long endTime = TimeUtil.getCurDateStamp();
                    entityWrapper.where(MessageFormat.format("praise_time >= {0} and {1} >= praise_time",startTime.toString() ,endTime.toString()));
                    if(comPraiseMapper.selectCount(entityWrapper) == 1){
                        DistributeIntegralReqDto distributeIntegralReqDto = new DistributeIntegralReqDto();
                        DistributeIntegralReqDto.DistributeIntegralReqData distributeIntegralReqData = distributeIntegralReqDto.dataInstance();
                        distributeIntegralReqData.setRemark(FlowTypeEnum.THUMBS);
                        distributeIntegralReqData.setRelevantId(userId);
                        distributeIntegralReqDto.setData(distributeIntegralReqData);
                        FinancialDetailsResData financialDetails = integralService.distributeIntegralByRemarkInt(distributeIntegralReqDto,maijiToken).getData();
                        outPutDto.setData(financialDetails);
                    }

                }else {
                    outPutDto.setStatus(Status.ERROR);
                    outPutDto.setMessage("点赞失败");
                }
            }

//            if(msgInfo.getPriority() == 0 && msgInfo.getPraise_count() >= 5){
//                msgInfo.setPriority(1);
//            }

            comMsgInfoMapper.updateById(msgInfo);
            outPutDto.setStatus(Status.SUCCESS);
            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());
            return outPutDto;
        }
    }

    /**
     * 取消动态的点赞
     * @param inputDto
     * @param maijiToken
     * @return
     */
    @Override
    public BaseOutPutDto<String> cancelPraise(@RequestBody BaseInputDto<IdInputDto> inputDto, @RequestHeader("maijiToken")String maijiToken){

        BaseOutPutDto<String> outPutDto = new BaseOutPutDto();

        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();
        try{

            ComPraise comPraise = new ComPraise();
            comPraise.setPraiserId(userId);
            comPraise.setBelongId(inputDto.getData().getId());
            comPraise.setDel(0);
            ComMsgInfo msgInfo = comMsgInfoMapper.selectById(inputDto.getData().getId());


            if(comPraiseMapper.update(new ComPraise().setDel(1),new EntityWrapper(comPraise)) > 0){
                msgInfo.setPraise_count(msgInfo.getPraise_count()-1);
                outPutDto.setStatus(Status.SUCCESS);
                outPutDto.setMessage("取消成功");
            }else{
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("取消失败");
            }
            comMsgInfoMapper.updateById(msgInfo);
            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage("取消失败");
            return outPutDto;
        }
    }


    /**
     * 动态点赞列表
     * @param inputDto
     * @return
     */
    public BaseOutPutDto<List<UserInfoResData>>praiseList(@RequestBody BaseInputDto<IdInputDto>inputDto){
        BaseOutPutDto<List<UserInfoResData>> praiseOutputs = new BaseOutPutDto<>();
        try{

            ComPraise newPraise = new ComPraise();
            newPraise.setBelongId(inputDto.getData().getId());
            List<UserInfo> praises = comPraiseMapper.praiseList(inputDto.getData().getId());
            List<UserInfoResData> userinfoRes = new ArrayList<>();
            for (UserInfo userInfo :praises
                 ) {
                UserInfoResData userInfoResData = new UserInfoResData();
                copyProperties(userInfo,userInfoResData);
                userinfoRes.add(userInfoResData);
            }
            praiseOutputs.setData(userinfoRes);
            praiseOutputs.setStatus(Status.SUCCESS);
            return praiseOutputs;
        }catch (Exception exc){
            praiseOutputs.setStatus(Status.ERROR);
            return praiseOutputs;
        }

    }

}
